package main

import (
	"go.uber.org/zap"
	"gorm.io/gorm"
	"sheep_script/core"
	"sheep_script/global"
	"sheep_script/initialize"
	"sheep_script/model"
	"sheep_script/model/order"
	"sheep_script/model/shop"
	"sheep_script/model/sponsor"
	"sheep_script/model/user"
	"time"
)

func init() {
	initialize.InitConfig()
	global.Logger = core.InitLogger()
	initialize.InitDB()
}

func main() {
	// 一分钟跑一次
	for {
		cancelShopOrder()
		cancelSponsorOrder()
		confirmShopOrder()
		time.Sleep(1 * time.Minute)
	}
}

func cancelShopOrder() {
	nowTime := time.Now().Add(-30 * time.Minute)

	// 查询数据
	var orderList []order.ShopOrders
	err := global.Mysql.Model(order.ShopOrders{}).
		Where("order_status = ?", order.ShopOrdersStatusWait).
		Where("created_at < ?", nowTime).
		Where("deleted", model.DeletedNo).
		Find(&orderList).Error
	if err != nil {
		global.Logger.Error("userSponsor-err:", zap.Error(err))
		return
	}

	var orderMasterIds []uint
	for _, v := range orderList {
		orderMasterIds = append(orderMasterIds, v.OrderMasterID)
	}

	var orderMasterList []order.ShopMasterOrders
	err = global.Mysql.Model(order.ShopMasterOrders{}).
		Where("id in ?", orderMasterIds).
		Find(&orderMasterList).Error
	if err != nil {
		global.Logger.Error("userSponsor-err:", zap.Error(err))
		return
	}

	var userIntegralListMap = map[uint]struct {
		UserId   uint
		Integral int
		SourceId uint
	}{}

	orderMasterListMap := map[uint]order.ShopMasterOrders{}
	for _, v := range orderMasterList {
		orderMasterListMap[v.ID] = v
		if _, ok := userIntegralListMap[v.ID]; ok {
			userIntegral := userIntegralListMap[v.ID]
			userIntegral.UserId += v.UserID
			userIntegralListMap[v.ID] = userIntegral
		}
	}

	// 获取所有的主订单id
	var orderIds []uint
	var goodsList []shop.ShopGoods
	for _, v := range orderList {
		orderIds = append(orderIds, v.ID)
		goodsList = append(goodsList, shop.ShopGoods{
			ID:       v.GoodsID,
			Quantity: v.Quantity,
		})

		if _, ok := userIntegralListMap[v.OrderMasterID]; ok {
			userIntegral := userIntegralListMap[v.OrderMasterID]
			userIntegral.UserId = orderMasterListMap[v.ID].UserID
			userIntegral.Integral += v.OrderIntegral
			userIntegral.SourceId = v.OrderMasterID
			userIntegralListMap[v.OrderMasterID] = userIntegral
		} else {
			userIntegralListMap[v.OrderMasterID] = struct {
				UserId   uint
				Integral int
				SourceId uint
			}{
				UserId:   orderMasterListMap[v.OrderMasterID].UserID,
				Integral: v.OrderIntegral,
				SourceId: v.OrderMasterID,
			}
		}
	}

	err = global.Mysql.Transaction(func(tx *gorm.DB) error {
		// 将主订单更新为取消状态
		err = tx.Model(order.ShopMasterOrders{}).
			Where("id IN ?", orderMasterIds).
			Where("deleted", model.DeletedNo).
			Where("order_status = ?", order.ShopMasterOrdersStatusWait).
			Updates(map[string]interface{}{"order_status": order.ShopOrdersStatusCancel}).
			Error
		if err != nil {
			return err
		}

		// 将子订单更新为取消状态
		err = tx.Model(order.ShopOrders{}).
			Where("id IN?", orderIds).
			Where("deleted", model.DeletedNo).
			Where("order_status =?", order.ShopOrdersStatusWait).
			Updates(map[string]interface{}{"order_status": order.ShopOrdersStatusCancel}).
			Error
		if err != nil {
			return err
		}

		// 将商品库存回滚
		for _, item := range goodsList {
			err = tx.Model(shop.ShopGoods{}).
				Where("id = ?", item.ID).
				Update("quantity", gorm.Expr("quantity + ?", item.Quantity)).
				Error
			if err != nil {
				return err
			}
		}

		// 将用户的积分回滚
		for _, item := range userIntegralListMap {
			if item.Integral == 0 {
				continue
			}
			err = tx.Model(user.Users{}).
				Where("id = ?", item.UserId).
				Update("integral", gorm.Expr("integral + ?", item.Integral)).Error
			if err != nil {
				return err
			}
			err = tx.Model(user.UserIntegralRecords{}).
				Where("user_id = ?", item.UserId).
				Where("source_id = ?", item.SourceId).
				Update("deleted", 1).Error
			if err != nil {
				return err
			}
		}

		return nil
	})

	if err != nil {
		global.Logger.Error("cancelShopOrder-err:", zap.Error(err))
	}
}

func cancelSponsorOrder() {
	nowTime := time.Now().Add(-30 * time.Minute)

	// 查询数据
	var orderList []order.SponsorOrders
	err := global.Mysql.Model(order.SponsorOrders{}).
		Where("order_status = ?", order.SponsorOrdersStatusWait).
		Where("created_at < ?", nowTime).
		Where("deleted", model.DeletedNo).
		Find(&orderList).Error
	if err != nil {
		global.Logger.Error("userSponsor-err:", zap.Error(err))
		return
	}

	var orderMasterIds []uint
	for _, v := range orderList {
		orderMasterIds = append(orderMasterIds, v.OrderMasterID)
	}

	// 查询主订单列表
	var orderMasterList []order.SponsorMasterOrders
	err = global.Mysql.Model(order.SponsorMasterOrders{}).
		Where("id in ?", orderMasterIds).
		Where("deleted", model.DeletedNo).
		Find(&orderMasterList).Error
	if err != nil {
		global.Logger.Error("userSponsor-err:", zap.Error(err))
		return
	}

	var userIntegralListMap = map[uint]struct {
		UserId   uint
		Integral int
		SourceId uint
	}{}

	orderMasterListMap := map[uint]order.SponsorMasterOrders{}
	for _, v := range orderMasterList {
		if _, ok := userIntegralListMap[v.ID]; ok {
			userIntegral := userIntegralListMap[v.ID]
			userIntegral.UserId += v.UserID
			userIntegralListMap[v.ID] = userIntegral
		}
		orderMasterListMap[v.ID] = v
	}

	// 获取所有的主订单id
	var orderIds []uint
	var goodsList []sponsor.SponsorGoods
	for _, v := range orderList {
		orderMasterIds = append(orderMasterIds, v.OrderMasterID)
		orderIds = append(orderIds, v.ID)
		goodsList = append(goodsList, sponsor.SponsorGoods{
			ID:       v.GoodsID,
			Quantity: v.Quantity,
		})

		if _, ok := userIntegralListMap[v.OrderMasterID]; ok {
			userIntegral := userIntegralListMap[v.OrderMasterID]
			userIntegral.UserId = orderMasterListMap[v.ID].UserID
			userIntegral.Integral += v.OrderIntegral
			userIntegral.SourceId = v.OrderMasterID
			userIntegralListMap[v.OrderMasterID] = userIntegral
		} else {
			userIntegralListMap[v.OrderMasterID] = struct {
				UserId   uint
				Integral int
				SourceId uint
			}{
				UserId:   orderMasterListMap[v.ID].UserID,
				Integral: v.OrderIntegral,
				SourceId: v.OrderMasterID,
			}
		}
	}

	err = global.Mysql.Transaction(func(tx *gorm.DB) error {
		// 将主订单更新为取消状态
		err = tx.Model(order.SponsorMasterOrders{}).
			Where("id IN ?", orderMasterIds).
			Where("deleted", model.DeletedNo).
			Where("order_status = ?", order.SponsorMasterOrdersStatusWait).
			Updates(map[string]interface{}{"order_status": order.SponsorMasterOrdersStatusCancel}).
			Error
		if err != nil {
			return err
		}

		// 将子订单更新为取消状态
		err = tx.Model(order.SponsorOrders{}).
			Where("id IN?", orderIds).
			Where("deleted", model.DeletedNo).
			Where("order_status =?", order.SponsorOrdersStatusWait).
			Updates(map[string]interface{}{"order_status": order.SponsorOrdersStatusCancel}).
			Error
		if err != nil {
			return err
		}

		// 将商品库存回滚
		for _, item := range goodsList {
			err = tx.Model(sponsor.SponsorGoods{}).
				Where("id = ?", item.ID).
				Update("quantity", gorm.Expr("quantity + ?", item.Quantity)).
				Error
			if err != nil {
				return err
			}
		}

		// 将用户的积分回滚
		for _, item := range userIntegralListMap {
			if item.Integral == 0 {
				continue
			}
			err = tx.Model(user.Users{}).
				Where("id = ?", item.UserId).
				Update("integral", gorm.Expr("integral + ?", item.Integral)).Error
			if err != nil {
				return err
			}
			err = tx.Model(user.UserIntegralRecords{}).
				Where("user_id = ?", item.UserId).
				Where("source_id = ?", item.SourceId).
				Update("deleted", 1).Error
			if err != nil {
				return err
			}
		}
		return nil
	})

	if err != nil {
		global.Logger.Error("cancelShopOrder-err:", zap.Error(err))
	}
}

func confirmShopOrder() {

	// 14天自动收货
	nowTime := time.Now().Add(-14 * 24 * time.Hour)

	// 查询数据
	var orderList []order.ShopOrders
	err := global.Mysql.Model(order.ShopOrders{}).
		Where("order_status = ?", order.ShopOrdersStatusDelivery).
		Where("updated_at < ?", nowTime).
		Where("deleted", model.DeletedNo).
		Find(&orderList).Error
	if err != nil {
		global.Logger.Error("userSponsor-err:", zap.Error(err))
		return
	}

	var orderMasterIds []uint
	var orderIds []uint
	for _, item := range orderList {
		orderMasterIds = append(orderMasterIds, item.OrderMasterID)
		orderIds = append(orderIds, item.ID)
	}

	err = global.Mysql.Transaction(func(tx *gorm.DB) error {
		// 将主订单更新为取消状态
		err = tx.Model(order.ShopMasterOrders{}).
			Where("id IN ?", orderMasterIds).
			Where("deleted", model.DeletedNo).
			Where("order_status = ?", order.ShopOrdersStatusDelivery).
			Updates(map[string]interface{}{"order_status": order.ShopOrdersStatusCompleted}).
			Error
		if err != nil {
			return err
		}

		// 将子订单更新为取消状态
		err = tx.Model(order.ShopOrders{}).
			Where("id IN?", orderIds).
			Where("deleted", model.DeletedNo).
			Where("order_status =?", order.ShopOrdersStatusDelivery).
			Updates(map[string]interface{}{"order_status": order.ShopOrdersStatusCompleted}).
			Error
		if err != nil {
			return err
		}

		return nil
	})

}
